<?php


namespace PKApp\Model\Classes;

use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\MatchHelper;
use PKFrame\Service;

class FieldService extends Service
{

    public function __construct()
    {
        parent::__construct();
    }

    protected function db(): FieldDateBase
    {
        return new FieldDateBase();
    }

    public function ServiceByModel(): ModelService
    {
        static $cls;
        !empty($cls) ?: $cls = new ModelService();
        return $cls;
    }

    public function GetList($viewParams = [], $viewField = '*')
    {
        return $this->db()
            ->Where($viewParams)
            ->OrderBy('listSort', 'asc')
            ->OrderBy('id', 'asc')
            ->Select($viewField)
            ->ToList();
    }

    public function GetListByModelId($model_id, $viewField = '*')
    {
        $params = ['modelId' => $model_id];
        if (stristr(strtolower(request()->referer()), 'content/adminsetcontent')) {
            $params['isShow'] = 1;
        }
        return $this->GetList($params, $viewField);
    }

    public function GetEntity($viewParams = [], $viewField = '*'): ?array
    {
        $entity = $this->db()->Where($viewParams)->Select($viewField)->First();
        if (is_array($entity)) {
            if (array_key_exists('power', $entity)) {
                $entity['power'] = Arrays::Unserialize($entity['power']);
            }
            if (array_key_exists('setting', $entity)) {
                $entity['setting'] = Arrays::Unserialize($entity['setting']);
            }
        }
        return $entity;
    }

    public function CheckExistsAndCreate($post)
    {
        $modelId = $post['modelId'];
        $enName = $post['field'];
        // 合法性字符
        MatchHelper::MatchFormat('letter_', $enName, 'ModelField_NameError');
        // 检查字段在表中是否已经存在
        $fieldEntity = $this->GetEntity([
            'modelId' => $modelId, 'field' => $enName
        ]);
        empty($fieldEntity) ?: $this->noticeByJson('ModelField_NameExists', 'model', $modelId . ' > ' . $enName);
        // 检查字段在实体表中是否已经存在
        $modelEntity = $this->ServiceByModel()->interface_getEntityById($modelId);
        $tableName = $this->ServiceByModel()->GetTableNameByModelId($modelId);
        $isExists = $this->db()->CheckFieldExists($tableName, $enName);
        if (!$isExists && ($modelEntity['modelType'] == 'content')) {
            $tableName_data = $tableName . '_data';
            $isExists = $this->db()->CheckFieldExists($tableName_data, $enName);
        }
        !$isExists ?: $this->noticeByJson('ModelField_NameExists', 'model', $tableName . ' > ' . $enName);
        // 创建实体表字段
        // 判断是否为列表字段
        if ($modelEntity['modelType'] == 'content' && $post['isList'] == 1) {
            $this->db()->AddFieldChange($tableName, $post);
        } elseif (isset($tableName_data)) {
            $this->db()->AddFieldChange($tableName_data, $post);
        } else {
            $this->db()->AddFieldChange($tableName, $post);
        }
    }

    public function DropField($id_model, $id_field)
    {
        // 检查字段在实体表中是否已经存在
        $entity_model = $this->ServiceByModel()->interface_getEntityById($id_model);
        $name_table = $this->ServiceByModel()->GetTableNameByModelId($id_model);
        // 检查字段在表中是否已经存在
        $entity_field = $this->interface_getEntityById($id_field);
        $name_field = $entity_field['field'];
        $isExists_field = $this->db()->CheckFieldExists($name_table, $name_field);
        if (!$isExists_field && ($entity_model['modelType'] == 'content')) {
            $isExists_field = $this->db()->CheckFieldExists($name_table .= '_data', $name_field);
        }
        !$isExists_field ?: $this->db()->DropFieldChange($name_table, $name_field);
    }

    public function interface_getEntityById($id, $viewField = '*')
    {
        return $this->getEntityById($id, 'ModelField_IdEmpty', 'ModelField_NoExists', $viewField);
    }

    public function saveCache($modelId)
    {
        $fieldList = $this->GetList(['modelId' => $modelId, 'isShow' => 1]);
        $search = $index = $notNull = [];
        $cache = ['fieldList' => [], 'isEmpty' => [], 'isList' => [], 'isSearch' => [],];
        foreach ($fieldList as $k => $v) {
            $v['setting'] = Arrays::Unserialize($v['setting']);
            $cache['fieldList'][$v['field']] = $v;
            if ($v['isSearch'])
                $search[] = $v['field'];
            if ($v['isList'])
                $index[] = $v['field'];
            if ($v['isEmpty'])
                $notNull[] = $v['field'];
        }
        $cache['isEmpty'] = $notNull;
        $cache['isList'] = $index;
        $cache['isSearch'] = $search;
        cache()->Disk()->WriteByData('Model_' . $modelId, $cache);
    }
}